#include<iostream>
#include<semaphore.h>
#include<pthread.h>
#include<unistd.h>
using namespace std;

class Sem
{
  public:
    Sem(int num)
    {
      sem_init(&sem,0,num);
    }
    void P()
    {
      sem_wait(&sem);
    }
    void V()
    {
      sem_post(&sem);
    }
    ~Sem()
    {
      sem_destroy(&sem);
    }
  private:
    sem_t sem;
};

Sem sem(1);
int tickets=1000;
void* Gettick(void *arg)
{
  string str=(char*)arg;
  while(true)
  {
    sem.P();
    if(tickets>0)
    {
      usleep(1000);
      cout<<str<<" get tickets"<<" "<<tickets--<<endl;
      sem.V();
      usleep(10000);
    }
    else
    {
      sem.V();
      break;
    }
  }
  cout<<str<<" quit"<<endl;
  pthread_exit((void*)0);
}
int main()
{
  pthread_t tid1,tid2,tid3;
  pthread_create(&tid1,nullptr,Gettick,(void*)"thread 1");
  pthread_create(&tid2,nullptr,Gettick,(void*)"thread 2");
  pthread_create(&tid3,nullptr,Gettick,(void*)"thread 3");

  pthread_join(tid1,nullptr);
  pthread_join(tid2,nullptr);
  pthread_join(tid3,nullptr);

  return 0;
}
